/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package tijdserver;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.RSAPrivateKeySpec;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.Cipher;
import util.Message;
import util.NetwerkComponent;
import util.Sniffer;
import util.SecurityManager;

/**
 *
 * @author roel
 */
public class TijdServerImpl implements TijdServer {

    private static int IDCounter = 0;
    private String ID;
    private Sniffer sniffy;

    public TijdServerImpl() {
        ID = "TS-id" + IDCounter;
        IDCounter++;
    }

    public void sendMessage(Message msg, NetwerkComponent sender) {
     
            if (sniffy != null) {
                sniffy.readTransmission(msg, sender, this);
            }
            if(msg.getMessageType() == Message.MessageType.TS_REQ){
                byte[] data = (byte[]) msg.getData().get("Signature");

                ArrayList<Object> toSign = new ArrayList<Object>();
                Long time = System.currentTimeMillis();
                toSign.add(data);
                toSign.add(time);
                byte[] toReturn = SecurityManager.signData(toSign,"./TSPrivate.key");

                HashMap<String, Object> send= new HashMap<String, Object>();
                send.put("Signature", data);
                send.put("Timestamp",time);
                send.put("SignTS",toReturn);
                sender.sendMessage(new Message(Message.MessageType.TS_ANSWER, send), this);
        }
    }

    @Override
    public String toString() {
        return ID;
    }

    public void addSniffer(Sniffer sniffer) {
        sniffy = sniffer;
        System.out.println("Sniffer added");
    }

    public void removeSniffer() {
        sniffy = null;
        System.out.println("Sniffer removed");
    }
}
